package chances.system.operator.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import chances.commons.crypto.DateUtils;
import chances.system.operator.entity.MgmtInfo;
import chances.system.operator.repo.MgmtInfoRepository;

@Service
public class MgmtInfoService extends BaseService{
	
	@Autowired
	MgmtInfoRepository mgmtInfoRepository;
	
    public MgmtInfo saveInfo(MgmtInfo info, MultipartFile faviconFile,
            MultipartFile iconFile, MultipartFile logoFile) throws IOException {
        List<String> relPaths = new ArrayList<String>();
        
        if (faviconFile.getSize()>0) {
            relPaths.add(info.getFavicon());
            String relPath = "info/" + DateUtils.dateToYYYYMMDD(new Date()) + "/"
                    + UUID.randomUUID().toString() + ".png";
            File destFile = getSitePicturePath(relPath);
            FileUtils.copyInputStreamToFile(faviconFile.getInputStream(), destFile);
            info.setFavicon(relPath);
        }
        if (iconFile.getSize()>0) {
            relPaths.add(info.getIcon());
            String relPath = "info/" + DateUtils.dateToYYYYMMDD(new Date()) + "/"
                    + UUID.randomUUID().toString() + ".png";
            File destFile = getSitePicturePath(relPath);
            FileUtils.copyInputStreamToFile(iconFile.getInputStream(), destFile);
            info.setIcon(relPath);
        }
        if (logoFile.getSize()>0) {
            relPaths.add(info.getLogo());
            String relPath = "info/" + DateUtils.dateToYYYYMMDD(new Date()) + "/"
                    + UUID.randomUUID().toString() + ".png";
            File destFile = getSitePicturePath(relPath);
            FileUtils.copyInputStreamToFile(logoFile.getInputStream(), destFile);
            info.setLogo(relPath);
        }
        mgmtInfoRepository.save(info);
        removeSiteImage(relPaths);
        return info;
    }
    
    public MgmtInfo save(MgmtInfo info) {
        mgmtInfoRepository.save(info);
        return info;
    }
    
    public MgmtInfo findById(Long id) {
        return mgmtInfoRepository.findOne(id);
    }
    
    public MgmtInfo findFirstOrDeFault() {
        return mgmtInfoRepository.findFirstOrDeFault();
    }
}